home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / pluginy Firefox / 8434 / 8434.xpi / chrome / content / GoogleRedesignedStyle.js < prev    next >
Text File  |  2009-11-16  |  20KB  |  206 lines

  1. function GoogleRedesignedStyle(o) {
  2.     if (typeof o == "string") {
  3.         this.node = this.ds.getNode(o);
  4.     } else if (o) {
  5.         this.node = o;
  6.     } else {
  7.         this.node = this.ds.getAnonymousNode();
  8.     }
  9.     this._description = null;
  10.     this._enabled = null;
  11.     this._customized = null;
  12.     this._code = null;
  13.     this._originalCode = null;
  14.     this._global = null;
  15.     this._domains = null;
  16.     this._siteURLPrefixes = null;
  17.     this._siteURLs = null;
  18.     this._namespaces = null;
  19.     this._treeDisplayCode = null;
  20.     this._appliesToDisplay = null;
  21.     this._namespaceNames = null;
  22.     this._updateURL = null;
  23.     this._neverUpdate = null;
  24. }
  25. GoogleRedesignedStyle.prototype = {containerURI: "urn:googleredesigned:userstyles", descriptionURI: "urn:googleredesigned#description", enabledURI: "urn:googleredesigned#enabled", customizedURI: "urn:googleredesigned#customized", originalCodeURI: "urn:googleredesigned#originalCode", codeURI: "urn:googleredesigned#code", siteURLURI: "urn:googleredesigned#url", updateURLURI: "urn:googleredesigned#updateURL", siteURLPrefixURI: "urn:googleredesigned#urlPrefix", siteDomainURI: "urn:googleredesigned#domain", globalStyleURI: "urn:googleredesigned#global", namespaceURI: "urn:googleredesigned#namespace", neverUpdateURI: "urn:googleredesigned#neverUpdate", documentRulePrefix: "@-moz-document ", copy: function (newStyle) {newStyle.description = this.description;newStyle.customized = this.customized;newStyle.originalCode = this.originalCode;newStyle.code = this.code;newStyle.siteURLs = this.siteURLs;if (this.updateURL) {newStyle.updateURL = this.updateURL;}newStyle.siteURLPrefixes = this.siteURLPrefixes;newStyle.domains = this.domains;newStyle.global = this.global;newStyle.namespaces = this.namespaces;newStyle.neverUpdate = this.neverUpdate;newStyle.enabled = this.enabled;}, applyArray: function (uri, values) {var valueArray;if (values instanceof Array) {valueArray = values;} else {valueArray = [];while (values.hasMoreElements()) {valueArray.push(values.getNext());}}var targets = this.node.getTargets(uri);while (targets.hasMoreElements()) {var target = targets.getNext();this.node.removeTarget(uri, target);}for (var i = 0; i < valueArray.length; i++) {this.node.addTarget(uri, valueArray[i]);}}, applyValue: function (uri, value) {var oldValue = this.node.getTarget(uri);if (oldValue) {this.node.modifyTarget(uri, oldValue, value);} else {this.node.addTarget(uri, value);}}, register: function () {googleredesignedCommon.registerStyle(this.uri, this.code);}, unregister: function () {googleredesignedCommon.unregisterStyle(this.uri, this.code);}, get uri() {return this.node.source.Value;}, get description() {if (this._description) {return this._description;}var descriptionLiteral = this.node.getTarget(this.descriptionURI);this._description = descriptionLiteral != null ? descriptionLiteral.getValue() : "";return this._description;}, set description(description) {this.applyValue(this.descriptionURI, description);this._description = null;}, get enabled() {if (this._enabled != null) {return this._enabled;}var enabledLiteral = this.node.getTarget(this.enabledURI);this._enabled = enabledLiteral != null ? enabledLiteral.getValue() == "true" : false;return this._enabled;}, set enabled(enabled) {var newTarget;if (enabled) {this.register();} else {this.unregister();}this.applyValue(this.enabledURI, enabled ? "true" : "false");this._enabled = null;}, enableWithoutRegister: function () {this.applyValue(this.enabledURI, "true");this._enabled = null;}, get enabledString() {return "" + this.enabled;}, set enabledString(enabledString) {this.enabled = enabledString == "true";}, get customized() {if (this._customized) {return this._customized;}var customizedLiteral = this.node.getTarget(this.customizedURI);this._customized = customizedLiteral != null ? customizedLiteral.getValue() == "true" : false;return this._customized;}, set customized(customized) {this.applyValue(this.customizedURI, customized ? "true" : "false");this._customized = null;}, get code() {if (this._code) {return this._code;}var codeLiteral = this.node.getTarget(this.codeURI);this._code = codeLiteral != null ? codeLiteral.getValue() : "";return this._code;}, set code(code) {this.applyValue(this.codeURI, code);this._code = null;}, get originalCode() {if (this._originalCode) {return this._originalCode;}var originalCodeLiteral = this.node.getTarget(this.originalCodeURI);this._originalCode = originalCodeLiteral != null ? originalCodeLiteral.getValue() : this.code;return this._originalCode;}, set originalCode(originalCode) {this.applyValue(this.originalCodeURI, originalCode);this._originalCode = null;}, get global() {if (this._global != null) {return this._global;}var globalLiteral = this.node.getTarget(this.globalStyleURI);this._global = globalLiteral != null ? globalLiteral.getValue() == "true" : false;return this._global;}, set global(globalStyle) {this.applyValue(this.globalStyleURI, globalStyle ? "true" : "false");this._global = null;}, get domains() {if (this._domains) {return this._domains;}this._domains = this.node.getTargets(this.siteDomainURI);return this._domains;}, set domains(domains) {this.applyArray(this.siteDomainURI, domains);this._domains = null;}, get siteURLPrefixes() {if (this._siteURLPrefixes) {return this._siteURLPrefixes;}this._siteURLPrefixes = this.node.getTargets(this.siteURLPrefixURI);return this._siteURLPrefixes;}, set siteURLPrefixes(prefixes) {this.applyArray(this.siteURLPrefixURI, prefixes);this._siteURLPrefixes = null;}, get siteURLs() {if (this._siteURLs) {return this._siteURLs;}this._siteURLs = this.node.getTargets(this.siteURLURI);return this._siteURLs;}, set siteURLs(urls) {this.applyArray(this.siteURLURI, urls);this._siteURLs = null;}, get namespaces() {if (this._namespaces) {return this._namespaces;}this._namespaces = this.node.getTargets(this.namespaceURI);return this._namespaces;}, set namespaces(namespaces) {this.applyArray(this.namespaceURI, namespaces);this._namespaces = null;}, get treeDisplayCode() {if (this._treeDisplayCode) {return this._treeDisplayCode;}this._treeDisplayCode = this.code.substring(0, 100).replace(/\n/g, " ");return this._treeDisplayCode;}, get appliesToDisplayArray() {if (this.global) {var namespaceNames = this.namespaceNames;if (namespaceNames.length > 0) {return namespaceNames;}return [STRINGS.getString("globalDisplay")];}var components = [];var domains = this.domains;while (domains.hasMoreElements()) {googleredesignedCommon.addAsSet(components, domains.getNext().getValue());}var urlPrefixes = this.siteURLPrefixes;while (urlPrefixes.hasMoreElements()) {googleredesignedCommon.addAsSet(components, this.formatUrlPrefixForDisplay(urlPrefixes.getNext().getValue()));}var urls = this.siteURLs;while (urls.hasMoreElements()) {googleredesignedCommon.addAsSet(components, this.formatUrlForDisplay(urls.getNext().getValue()));}return components;}, getLastModifiedDate: function (passed) {var dsp = new GoogleRedesignedRDFDataSource(googleredesignedBrowserOverlay.getConfigUri());var te = dsp.getNode(passed);var tg = te.getTarget("urn:googleredesigned#lastModifiedDate");return tg.getValue();}, get appliesToDisplay() {if (this._appliesToDisplay) {return this._appliesToDisplay;}this._appliesToDisplay = this.appliesToDisplayArray.join(", ");return this._appliesToDisplay;}, formatUrlPrefixForDisplay: function (urlPrefix) {if (this.isUIUrl(urlPrefix)) {return STRINGS.getString("xulDisplay");}return urlPrefix + "*";}, formatUrlForDisplay: function (url) {if (this.isUIUrl(url)) {return STRINGS.getString("xulDisplay");}return url;}, isUIUrl: function (url) {return /^(chrome|about|x-jsd)/.test(url);}, get namespaceNames() {if (this._namespaceNames) {return this._namespaceNames;}var namespaces = this.namespaces;this._namespaceNames = [];while (namespaces.hasMoreElements()) {var currentNamespace = namespaces.getNext().getValue();switch (currentNamespace) {case googleredesignedCommon.XULNS:this._namespaceNames.push(STRINGS.getString("xulDisplay"));break;case googleredesignedCommon.HTMLNS:this._namespaceNames.push(STRINGS.getString("htmlDisplay"));break;default:this._namespaceNames[this._namespaceNames.length] = currentNamespace.substring(currentNamespace.lastIndexOf("/") + 1);}}return this._namespaceNames;}, getParameterizedURI: function (parameter) {if (this.uri.substring(0, 3) == "urn" || this.uri.substring(0, 3) == "rdf") {return null;}if (this.uri.indexOf("?") > -1) {return this.uri + "&" + parameter;}return this.uri + "?" + parameter;}, get updateURL() {if (this._updateURL) {return this._updateURL;}var updateURL = this.node.getTarget(this.updateURLURI);if (updateURL) {this._updateURL = updateURL.getValue();} else {this._updateURL = this.getParameterizedURI("raw");}return this._updateURL;}, set updateURL(updateURL) {this.applyValue(this.updateURLURI, updateURL);this._updateURL = null;}, get neverUpdate() {if (this._neverUpdate != null) {return this._neverUpdate;}var neverUpdateLiteral = this.node.getTarget(this.neverUpdateURI);this._neverUpdate = neverUpdateLiteral != null ? neverUpdateLiteral.getValue() == "true" : false;return this._neverUpdate;}, set neverUpdate(neverUpdate) {this.applyValue(this.neverUpdateURI, neverUpdate ? "true" : "false");this._neverUpdate = null;}, 
  26.  
  27.  
  28.  
  29.  
  30.  
  31.  
  32.  
  33.  
  34.  
  35.  
  36.  
  37.  
  38.  
  39.  
  40.  
  41.  
  42.  
  43.  
  44. checkForUpdate: function (callback) {
  45.  
  46.     if (this.neverUpdate) {callback(null);return;}
  47.     var updateURL = this.updateURL;
  48.     if (!updateURL) {callback(null);return;}
  49.     var tgu = this.updateURL;
  50.     var currentCode = this.originalCode;
  51.     var currentDescription = this.description;
  52.     var requestTimer = setTimeout(function () {
  53.         // clean up if old channel exists.  Should never happen really!
  54.         if(this.gChannel){
  55.             this.gChannel.cancel(Components.results.NS_BINDING_ABORTED);
  56.             this.gChannel=null;
  57.         }
  58.         GoogleRedesignedUpdateManager.googleredesignedupdateabortarray.push(currentDescription);
  59.         callback(null);
  60.     }, 30000);
  61.     //listener for the converted data
  62.     var listener2 ={
  63.     jj:"",
  64.      onDataAvailable : function(request, context, inputStream, offset, count)
  65.      {
  66.          var sStream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance().QueryInterface(Components.interfaces.nsIScriptableInputStream);
  67.          sStream.init(inputStream);
  68.          sStream.available();
  69.          while (sStream.available()) {
  70.             listener2.jj+=(sStream.read(count));
  71.          }
  72.      },
  73.  
  74.      onStartRequest : function(request, context){},
  75.  
  76.      onStopRequest : function(aRequest, context){
  77.      
  78.         clearTimeout(requestTimer);
  79.         if (aRequest.QueryInterface(Components.interfaces.nsIHttpChannel).responseStatus == 304){
  80.             callback(null);
  81.             return;
  82.         }
  83.         if (aRequest.QueryInterface(Components.interfaces.nsIHttpChannel).getResponseHeader("Content-Type").indexOf("application/x-gzip") != 0) {
  84.             GoogleRedesignedUpdateManager.googleredesignedupdateabortarray.push(currentDescription);
  85.             callback(null);
  86.             return;
  87.         }
  88.         if (!googleredesignedCommon.cssAreEqual(listener2.jj, currentCode)) {
  89.             GoogleRedesignedUpdateManager.googleredesignedupdatesuccessarray.push(currentDescription);
  90.             var dsp = new GoogleRedesignedRDFDataSource(googleredesignedBrowserOverlay.getConfigUri());
  91.             var te = dsp.getNode(tgu);
  92.             var tg = te.getTarget("urn:googleredesigned#lastModifiedDate");
  93.             var tm = tg.getValue();
  94.             te.modifyTarget("urn:googleredesigned#lastModifiedDate", tm, aRequest.QueryInterface(Components.interfaces.nsIHttpChannel).getResponseHeader("Last-Modified"));
  95.             dsp.save();
  96.             callback(listener2.jj);
  97.             return;
  98.         }
  99.         callback(null);     
  100.      }
  101.     };
  102.     var conv;
  103.     function StreamListener(aCallbackFunc) {
  104.       this.mCallbackFunc = aCallbackFunc;
  105.     }
  106.     StreamListener.prototype = {
  107.       mData: "",
  108.       // nsIStreamListener
  109.       onStartRequest: function (aRequest, aContext) {
  110.         this.mData = "";
  111.         //this.mCallbackFunc("started");
  112.         
  113.         // Attempt to gunzip
  114.         conv = Components.classes["@mozilla.org/streamconv;1?from=gzip&to=uncompressed"].createInstance(Components.interfaces.nsIStreamConverter);
  115.         conv.asyncConvertData("gzip", "uncompressed", listener2, aRequest);
  116.         conv.onStartRequest(aRequest, aContext);
  117.       },
  118.       onDataAvailable: function (aRequest, aContext, aStream, aSourceOffset, aLength) {
  119.           //really do the conversion
  120.           conv.onDataAvailable(aRequest, aContext, aStream,  aSourceOffset, aLength);    
  121.       },
  122.       onStopRequest: function (aRequest, aContext, aStatus) {
  123.         if (Components.isSuccessCode(aStatus)) {
  124.             // request was successfull
  125.             // this.mCallbackFunc(aRequest);
  126.             //result
  127.             //this.mCallbackFunc(this.mData);      
  128.             var status = {};
  129.             conv.onStopRequest(aRequest, aContext, aStatus);        
  130.         } else {
  131.             // request failed
  132.             //this.mCallbackFunc(aStatus);
  133.             clearTimeout(requestTimer);
  134.             GoogleRedesignedUpdateManager.googleredesignedupdateabortarray.push(currentDescription);
  135.             callback(null);
  136.         }
  137.         this.gChannel = null;
  138.       },
  139.       // nsIChannelEventSink
  140.       onChannelRedirect: function (aOldChannel, aNewChannel, aFlags) {
  141.         // if redirecting, store the new channel
  142.         gChannel = aNewChannel;
  143.         //this.mCallbackFunc(aNewChannel.name);
  144.       },
  145.       // nsIInterfaceRequestor
  146.       getInterface: function (aIID) {
  147.         try {
  148.           return this.QueryInterface(aIID);
  149.         } catch (e) {
  150.           throw Components.results.NS_NOINTERFACE;
  151.         }
  152.       },
  153.       // nsIProgressEventSink (not implementing will cause annoying exceptions)
  154.       onProgress : function (aRequest, aContext, aProgress, aProgressMax) { },
  155.       onStatus : function (aRequest, aContext, aStatus, aStatusArg) { },
  156.       // nsIHttpEventSink (not implementing will cause annoying exceptions)
  157.       onRedirect : function (aOldChannel, aNewChannel) { },
  158.       // we are faking an XPCOM interface, so we need to implement QI
  159.       QueryInterface : function(aIID) {
  160.         if (aIID.equals(Components.interfaces.nsISupports) ||
  161.             aIID.equals(Components.interfaces.nsIInterfaceRequestor) ||
  162.             aIID.equals(Components.interfaces.nsIChannelEventSink) || 
  163.             aIID.equals(Components.interfaces.nsIProgressEventSink) ||
  164.             aIID.equals(Components.interfaces.nsIHttpEventSink) ||
  165.             aIID.equals(Components.interfaces.nsIStreamListener))
  166.           return this;
  167.         throw Components.results.NS_NOINTERFACE;
  168.       }
  169.     };
  170.     // global channel
  171.     if(this.gChannel){
  172.         this.gChannel.cancel(Components.results.NS_BINDING_ABORTED);
  173.         this.gChannel = null;
  174.     }
  175.     // init the channel
  176.     // the IO service
  177.     var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
  178.     // create an nsIURI
  179.     var uri = ioService.newURI(updateURL += (updateURL.match(/\?/) == null ? "?" : "&") + (new Date).getTime(), null, null);
  180.     // get a channel for that nsIURI
  181.     this.gChannel = ioService.newChannelFromURI(uri);
  182.     // get an listener
  183.     var callbackFunc=function(g){alert(g)}
  184.     var listener = new StreamListener(callbackFunc);
  185.     this.gChannel.QueryInterface(Components.interfaces.nsIHttpChannel).setRequestHeader("If-Modified-Since",this.getLastModifiedDate(this.updateURL),false);
  186.     this.gChannel.notificationCallbacks = listener;
  187.     try {
  188.         this.gChannel.asyncOpen(listener, null);
  189.     } catch (ex) {
  190.         alert(updateURL);
  191.         callback(null);
  192.         return;
  193.     }
  194. },
  195. gChannel:null,
  196. save: function () {this.ds.getNode(this.containerURI).addChild(this.node);this.ds.save();}, getDatasourceURI: function () {var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);var prefPath = prefs.getCharPref("extensions.googleredesigned.fileURL");if (prefPath.length > 0) {return prefPath;}var file = Components.classes['@mozilla.org/file/directory_service;1'].getService(Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile);file.append("extensions");file.append("{cc85cd4e-5a5b-4eda-a25c-bdaffa93b406}");file.append("chrome");file.append("content");file.append("googleredesigned.rdf");var ioService = Components.classes['@mozilla.org/network/io-service;1'].getService(Components.interfaces.nsIIOService);if (!file.exists()) {var scriptableStream = Components.classes['@mozilla.org/scriptableinputstream;1'].getService(Components.interfaces.nsIScriptableInputStream);var channel = ioService.newChannel("chrome://googleredesigned/content/googleredesigned-default.rdf", null, null);var input = channel.open();scriptableStream.init(input);var data = scriptableStream.read(input.available());scriptableStream.close();input.close();var foStream = Components.classes['@mozilla.org/network/file-output-stream;1'].createInstance(Components.interfaces.nsIFileOutputStream);foStream.init(file, 2 | 8 | 32, 436, 0);foStream.write(data, data.length);foStream.close();}return ioService.newFileURI(file).spec;}, calculateMetadata: function (stylesheet) {var domains = [];var urlPrefixes = [];var urls = [];var namespaces = [];var isGlobal = false;for (var i = 0; i < stylesheet.cssRules.length; i++) {var rule = stylesheet.cssRules[i];var isDocRule;try {rule.QueryInterface(Components.interfaces.nsIDOMCSSMozDocumentRule);isDocRule = true;} catch (ex) {if (ex.name == "NS_NOINTERFACE") {isDocRule = false;if (rule.type == Components.interfaces.nsIDOMCSSRule.STYLE_RULE) {isGlobal = true;} else if (rule.type == Components.interfaces.nsIDOMCSSRule.UNKNOWN_RULE) {if (rule.cssText.indexOf("@namespace") == 0) {var start = rule.cssText.indexOf("url(");var end = rule.cssText.lastIndexOf(")");namespaces[namespaces.length] = rule.cssText.substring(start + 4, end);}}} else {throw ex;}}if (isDocRule) {var mozDocPosition = rule.cssText.indexOf(GoogleRedesignedStyle.prototype.documentRulePrefix);if (mozDocPosition == -1) {alert("Rule QIs to moz-document but moz-document string not found.");continue;}var mozDocEnd = rule.cssText.indexOf(" {");var sitesString = rule.cssText.substring(mozDocPosition + GoogleRedesignedStyle.prototype.documentRulePrefix.length, mozDocEnd - 1);var sites = sitesString.split(", ");for (var j = 0; j < sites.length; j++) {var openParenthesis = sites[j].indexOf("(\"");var site = sites[j].substring(openParenthesis + 2, sites[j].length - 2);var type = sites[j].substring(0, openParenthesis);switch (type) {case "url":urls[urls.length] = site;break;case "url-prefix":if (site.indexOf(":") == -1 || /^(^\/)*:\/?\/?$/.test(site)) {isGlobal = true;} else {urlPrefixes[urlPrefixes.length] = site;}break;case "domain":domains[domains.length] = site;break;default:alert("Unrecognized site rule type '" + type + "'.");}}}}this.global = isGlobal;this.namespaces = namespaces;this.domains = domains;this.siteURLs = urls;this.siteURLPrefixes = urlPrefixes;}, appliesToNamespace: function (namespace) {var styleNamespaces = this.namespaces;if (!styleNamespaces.hasMoreElements()) {return true;}while (styleNamespaces.hasMoreElements()) {if (styleNamespaces.getNext().getValue() == namespace) {return true;}}return false;}};
  197. GoogleRedesignedStyle.prototype.ds = new GoogleRedesignedRDFDataSource(GoogleRedesignedStyle.prototype.getDatasourceURI());
  198. var loadedListener;
  199. function GoogleRedesignedStylesheetLoadedListener(doc, errorListener, callback) {
  200.     loadedListener = this;
  201.     this.doc = doc;
  202.     this.errorListener = errorListener;
  203.     this.callback = callback;
  204. }
  205. GoogleRedesignedStylesheetLoadedListener.prototype = {checkStyleLoaded: function () {try {try {var stylesheet = loadedListener.doc.QueryInterface(Components.interfaces.nsIDOMDocumentStyle).styleSheets[0];stylesheet.cssRules.length;} catch (ex) {if (ex.name == "NS_ERROR_DOM_INVALID_ACCESS_ERR") {setTimeout(loadedListener.checkStyleLoaded, 100);} else {loadedListener.unregisterErrorListener();var data = {exception: ex, stylesheet: stylesheet, errors: loadedListener.errorListener.errors};loadedListener.callback(false, data);loadedListener.destroy();}return;}loadedListener.unregisterErrorListener();if (loadedListener.errorListener) {loadedListener.callback(true, {stylesheet: stylesheet, errors: loadedListener.errorListener.errors});} else {loadedListener.callback(true, {stylesheet: stylesheet, errors: []});}} catch (ex) {Components.utils.reportError(ex);alert(ex);}}, destroy: function () {loadedListener = null;}, unregisterErrorListener: function () {var consoleService = Components.classes['@mozilla.org/consoleservice;1'].getService(Components.interfaces.nsIConsoleService);consoleService.unregisterListener(loadedListener.errorListener);}};
  206.